from my_data.local_data import LocalData
from base_restful.http_utils import *
from base_restful.crm import *
from base_restful.goods import *
import time
from .const import BaseInfo

data = LocalData()
"""
目前采购单只支持一个商品的分配
"""


def erp_query_main_bill_list(order_id):
    """
    查询待分配采购单
    :return:
    """
    param = {"mainStatus": 0, "orderId": order_id, "pageSize": 10, "currentPage": 1}

    return http_post_json('/erp/purchase/queryMainBillList', param)['data']['data']


def erp_do_claim(main_bill_id):
    """
    认领采购单
    :return:
    """
    param = {"mainBillId": main_bill_id, "dealFlag": 1}
    return http_post_json('/erp/purchase/doClaim', param)


def erp_do_submit_to_approval(main_bill_id):
    data_ = erp_sort_get_sort_center()['data']
    sortCenterId = data_[0]['id']
    sortCenterName = data_[0]['name']
    """
    采购单确认分配
    :return:
    """
    param = {"mainBillId": main_bill_id, "sortCenterId": sortCenterId, "sortCenterName": sortCenterName}
    return http_post_json('/erp/purchase/doSubmitToApproval', param)


def erp_sort_get_sort_center():
    """
    采购单确认分配
    :return:
    """
    param = {"salesArea": BaseInfo.login.get_user()['areaList'][0]}
    return http_get('/erp/sort/getSortCenter', param)


def erp_get_main_bill_id_by_order_id(order_id):
    pass


def erp_query_main_bill_detail(main_bill_id):
    """
    查询采购单详情
    :return:
    """
    param = {"mainBillId": main_bill_id}
    return http_get('/erp/purchase/queryMainBillDetail', param)['data']


def erp_purchase_task_list(order_id):
    """
    获取分拣待处理采购任务
    :return: purchaseTaskListDtoList 数据集
    """
    print("获取分拣待处理采购任务", order_id)
    param = {"orderId": order_id, "pageSize": 100, "page": 1}
    return http_get('/erp/purchaseTask/listByPage', param)['data']


def erp_purchase_task_details(pt_id):
    """
    获取分拣任务详情
    :return: purchaseTaskListDtoList 数据集
    """
    print("获取分拣任务详情", pt_id)
    param = {}
    return http_get('/erp/purchaseTask/details/' + pt_id, param)['data']


def erp_query_employee_by_sort_center(sort_center_id):
    """
    通过分分拣中心获取分拣人员
    :return: purchaseTaskListDtoList 数据集
    """
    print("通过分分拣中心获取分拣人员", sort_center_id)
    param = {"sortCenterId": sort_center_id}
    return http_get('/erp/commonSearch/queryEmployeeBySortCenter', param)['data']


def erp_query_purchase_entry_list(order_id):
    """
    通过订单ID查询待入库的任务
    :return: purchaseEntryListDtoList 数据集
    """
    print("通过订单ID查询待入库的任务", order_id)
    param = {"orderId": order_id, "pageSize": 100, "page": 1}
    return http_get('/erp/purchaseEntry/listByPage', param)['data']


def erp_query_return_task_list(order_id):
    """
    获取待处理的退货任务
    :param order_id 订单ID
    :return: list 数据集
    """
    print("获取带出里的退货任务", order_id)
    param = {"orderId": order_id, "pageSize": 100, "page": 1}
    return http_get('/erp/returnTask/listByPage', param)['data']


def erp_query_return_entry_list(order_id):
    """
    获取退货待入库列表
    :param order_id 订单ID
    :return: list 数据集
    """
    print("获取退货待入库列表", order_id)
    param = {"orderId": order_id, "pageSize": 100, "page": 1}
    return http_get('/erp/returnTaskEntry/listByPage', param)['data']


def erp_query_return_entry_detail(returnTaskId):
    """
    获取退货待入库详情
    :param order_id 订单ID
    :return:
    """
    print("获取退货待入库详情", returnTaskId)
    param = {"returnTaskId": returnTaskId}
    return http_get('/erp/returnTaskEntry/detail', param)['data']


def erp_return_deal_or_deal_list(rt_id):
    """
    处理退货任务
    :param rt_id: erp_query_return_task_list[list][0].returnTaskId
    :return:
    """
    print("处理退货任务", rt_id)
    param = {"pickerId": "", "pickerName": "", "pickerRemarks": "", "returnTaskIdList": [rt_id]}
    return http_put_json('erp/returnTask/dealOrDealList', param)['data']


def erp_query_logistics():
    """
    获取物流商
    :return:
    """
    print("获取物流商")
    param = {}
    return http_get('/erp/commonSearch/queryLogistics', param)['data']


def erp_return_hand(order_id):
    wr_list = list(erp_query_return_task_list(order_id)['list'])
    for wr in wr_list:
        erp_return_deal_or_deal_list(wr['returnTaskId'])

    en_list = list(erp_query_return_entry_list(order_id)['list'])
    logistics = erp_query_logistics()[0]
    for en in en_list:
        en_detail = erp_query_return_entry_detail(en['returnTaskId'])
        param = {"deliveryOrderAttachment": "", "deliveryType": 0, "logisticsProvidersId": logistics['logisticsId'],
                 "logisticsProvidersName": logistics['logisticsName'],
                 "returnOrderAttachment": "", "returnTaskId": en['returnTaskId'], "goodsList": [
            ]}

        goods_list = []
        for g in en_detail['goodsList']:
            goods_list.append(
                {"goodsId": g['goodsId'], "qualifiedQuantity": g['returnQuantity'], "unqualifiedQuantity": 0,
                 "entryQuantity": g['returnQuantity']})
        param['goodsList'] = goods_list
        print(http_post_json("/erp/returnTaskEntry/entry", param), param)


def erp_query_purchase_entry_details(pt_id):
    """
    获取入库任务详情
    :return: purchaseTaskListDtoList 数据集
    """
    print("获取分拣任务详情", pt_id)
    param = {}
    return http_get('/erp/purchaseEntry/details/' + pt_id, param)['data']


def erp_query_purchase_out_list(order_id):
    """
    通过订单ID查询待入库的任务
    :return: purchaseStockOutListDtoList 数据集
    """
    print("通过订单ID查询待入库的任务", order_id)
    param = {"orderId": order_id, "pageSize": 100, "page": 1}
    return http_get('/erp/mainTask/listByPage', param)['data']


def erp_query_purchase_out_details(mt_id):
    """
    获取待出库详情
    :param mt_id erp_query_purchase_out_list[0].mainTaskId
    :return: purchaseTaskListDtoList 数据集
    """
    print("获取分拣任务详情", mt_id)
    param = {}
    return http_get('/erp/mainTask/details/' + mt_id, param)['data']


def erp_purchase_task_hand_deal(order_id):
    """
    通过订单id,处理分拣待处理任务
    :param order_id:
    :return:
    """
    print("处理分拣待处理任务", order_id)
    task_list = list(erp_purchase_task_list(order_id)['purchaseTaskListDtoList'])
    for task in task_list:
        purchaseTaskId = task['purchaseTaskId']
        detail = erp_purchase_task_details(purchaseTaskId)
        sortCenterId = detail['sortCenterId']
        employees = list(erp_query_employee_by_sort_center(sortCenterId))
        employee_id = employees[0]['userId']
        employee_name = employees[0]['userName']
        print("purchaseTaskId", purchaseTaskId)
        param = {"pickerId": employee_id, "pickerName": employee_name, "purchaseTaskId": purchaseTaskId,
                 "canNotSupplySkuList": []}
        deal = http_put_json("erp/purchaseTask/deal", param)
        print(deal, param)


def erp_purchase_task_stock_in(order_id):
    """
    通过订单id,全部入库
    :param order_id:
    :return:
    """
    print("通过订单id,全部入库", order_id)
    task_list = list(erp_query_purchase_entry_list(order_id)['purchaseEntryListDtoList'])
    for task in task_list:
        sortCenterId = task['sortCenterId']
        purchaseTaskId = task['purchaseTaskId']
        entry_details = erp_query_purchase_entry_details(purchaseTaskId)
        employees = list(erp_query_employee_by_sort_center(sortCenterId))
        employee_id = employees[0]['userId']
        employee_name = employees[0]['userName']
        param = {
            "entryAttachment": "group1/M00/00/25/CoFTol1KSwCAVFSJAACI-72XJSI427.png",
            "purchaseTaskId": purchaseTaskId
        }
        details = []
        for detail in entry_details['purchaseEntryGoodsDetailDtoList']:
            details.append({
                "skuId": detail['skuId'],
                "entryQuantity": detail['pendingEntryQuantity'],
                "partNumber": detail['partNumber']
            })
        param['purchaseEntryGoodsDoEntryDtoList'] = details
        doEntry = http_post_json("/erp/purchaseEntry/doEntry", param)
        print(doEntry, param)


def erp_purchase_task_stock_out(order_id):
    """
    通过订单id,全部出库
    :param order_id:
    :return:
    """
    print("通过订单id,全部出库", order_id)
    task_list = list(erp_query_purchase_out_list(order_id)['purchaseStockOutListDtoList'])
    for task in task_list:
        mainTaskId = task['mainTaskId']
        out_details = erp_query_purchase_out_details(mainTaskId)
        employee_name = BaseInfo.login.get_user()['userName']
        employee_id = BaseInfo.login.get_user()['userId']
        param = {
            "mainTaskId": mainTaskId,
            "stockOutAttachment": "group1/M00/00/25/CoFToV1KZ1GAZfJ7AACI-72XJSI004.png",
            "consignor": employee_id,
            "consignorRemarks": "自动脚本发货",
            "purchaseStockOutDoStockOutGoodsDtoList": out_details['purchaseStockOutGoodsDetailDtoList'],
            "consignorName": employee_name
        }
        doEntry = http_put_json("/erp/mainTask/doStockOut", param)
        print(doEntry, param)


def erp_do_distribute(main_bill_id):
    """
    采购单分配 目前只支持标准商品 且商品必须存在供应商
    :return:
    """
    rarr = []
    # mainBillId = main_bill_info['mainBillId']
    main_bill = erp_query_main_bill_detail(main_bill_id)
    salesAreaId = main_bill['salesAreaId']
    sub_bills = list(main_bill['subVoList'])
    for sub in sub_bills:
        goods_vo_ = sub['goodsVoList'][0]
        param = {"mainBillId": main_bill, "mainBillGoodsId": goods_vo_['mainBillGoodsId'],
                 "purchaseNum": goods_vo_['purchaseNum'],
                 "subBillGoodsId": goods_vo_['subBillGoodsId'], "subBillId": goods_vo_['subBillId']}
        print(http_post_json("/erp/purchase/doCancleDistribute", param), param)
        time.sleep(3)

    dlist = list(main_bill['mainGoodsVolist'])
    for main_detail in dlist:
        goods_id = main_detail['goodsId']
        mainBillGoodsId = main_detail['mainBillGoodsId']
        purchaseNum = main_detail['purchaseNum']
        supplier = goods_list_goods_purchase(goods_id, salesAreaId, 1)[0]
        supplierId = supplier['supplierId']
        supplierName = supplier['supplierName']
        purchasePrice = supplier['price']
        bank = crm_supplier_bank_and_type_by_id(supplierId)['bankCardInfos'][0]
        bankId = bank['bankId']
        param = {"goodsId": goods_id, "mainBillGoodsId": mainBillGoodsId,
                 "mainBillId": main_bill_id, "supplierId": supplierId,
                 "supplierName": supplierName, "purchasePrice": purchasePrice, "purchaseNum": purchaseNum,
                 "isCloudWarehouse": 0,
                 "cloudWarehouseId": "", "settlementType": 0, "bankId": bankId}
        rarr.append(http_post_json('/erp/purchase/doDistribute', param))
        time.sleep(3)
    return rarr
